<template>
    <el-dialog
        title="安全验证"
        :visible="dialogVisible"
        width="420px"
        custom-class="sms-dialog"
        :close-on-click-modal="false"
        append-to-body
        :before-close="handleClose">
        <div class="desc" v-if="!whiteList.includes(adminId)">
            当前行为属高敏感权限，基于账户安全考虑，请验证运营员手机号：<span style="color: #409EFF">{{ formData.mobile }}</span>
        </div>
        <div class="desc" v-else>
            当前行为属高敏感权限，但当前账号为<span style="color: #409EFF">白名单内账号</span>，故不需要短信安全验证，可直接点击确认操作
        </div>
        <el-form :model="formData" :rules="rules" ref="formRef" label-width="0" size="small">
            <el-form-item label="" prop="code" v-if="!whiteList.includes(adminId)">
                <el-input v-model="formData.code" placeholder="请输入短信验证码">
                    <template slot="append">
                        <el-button type="text" @click="getcode" :disabled="disabled">{{smsText}}</el-button>
                    </template>
                </el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="handleClose" size="small">取 消</el-button>
            <el-button type="primary" @click="submit" size="small">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>
export default {
    name: 'sms-verification',
    props: {
        options: {
            type: Object,
            default: () => ({ 
                visible: false,
                params: {} // 回调函数参数
            })
        }
    },
    data() {
        // function validatePhone(rule, value, callback) {
        //     if (!value) {
        //         callback(new Error('请输入手机号'))
        //     } else {
        //         if (!/^1[1-9]\d{9}$/.test(value.toString())) {
        //             callback(new Error('请正确输入手机号'))
        //         } else {
        //             callback()
        //         }
        //     }
        // }
        return {
            dialogVisible: false,
            disabled: false,
            smsText: '获取验证码',
            verified: false,
            formData: {
                mobile: window.location.hostname.includes('mycjj.com') ? '13588466018' : '13645810322', // 董丽琴 : 单梦航
                code: '',
                type: 0
            },
            adminId: this.$store.getters["user_info"].admin_id,
            whiteList: ['79', '130', '48', '58', '116'],
            rules: {
                mobile: [
                    { required: true, message: '请输入手机号', trigger: ['blur', 'change'] },
                    // { validator: validatePhone, trigger: 'blur' }
                ],
                code: [
                    { required: true, message: '请输入短信验证码', trigger: ['blur', 'change'] }
                ]
            },
            timer: null
        }
    },
    watch: {
        'options': {
            handler(val) {
                if (val.visible) {
                    this.dialogVisible = true
                    if (val.type) {
                        this.formData.type = val.type
                    } else {
                        this.$message.error('请传递type')
                    }
                }
            },
            immediate: true
        }
        
    },
    methods: {
        handleClose(done) {
            this.$refs.formRef.resetFields()
            this.dialogVisible = false
            this.handleClearInterval()
        },
        handleClearInterval() {
            this.disabled = false
            this.smsText = '获取验证码'
            clearInterval(this.timer) 
            this.timer = null
        },
        secondsCountDown(times, step = 1) {
            if (!Number.isInteger(times) && times < step) return
            let time = times
            const go = () => {
                this.smsText = time + 's 后重获取'
                time -= step
            }
            go()
            this.timer = setInterval(() => {
                if(time > step) {
                    go()
                } else {
                    this.handleClearInterval()
                }
            }, 1000)
        },
        getcode() {
            // 获取短信
            this.disabled = true
            this.$http.get('/captcha/index.php?act=captcha&op=getSmsCode', {params: { mobile: this.formData.mobile }})
            .then(res => {
                if (+res.code === 1) {
                    this.secondsCountDown(60, 1)
                    this.$message.success('短信已成功发送至: ' + this.formData.mobile)
                } else {
                    this.$message.error(`${res.msg}`)
                    this.disabled = false
                }
            }).catch(error => {
                this.disabled = false
                error && this.$message.error(`${error}`)
            })
        },
        async submit() {
            try {
                if (this.whiteList.includes(this.adminId)) {
                    this.$emit('update', this.options.params)
                    this.verified = true
                    this.handleClose()
                    return
                }
                this.$refs.formRef.validate(valid => {
                    if (valid) {
                        const { mobile, code, type } = this.formData
                        // 校验短信
                        this.$http.post('/captcha/index.php?act=captcha&op=checkSmsCode', { mobile, code, type })
                        .then(res => {
                            if (+res.code === 1) {
                                this.$emit('update', this.options.params)
                                this.verified = true
                                this.handleClose()
                            } else {
                                throw res.msg
                            }
                        }).catch(error => {
                            error && this.$message.error(`${error}`)
                        })
                    }
                })
            } catch (error) {
                error && this.$message.error(`${error}`)
            }
        }
    }
}
</script>
<style lang="scss">
.sms-dialog {
    .el-dialog__body {
        padding-top: 20px;
        padding-bottom: 20px;
        .el-input--small, .el-input__inner {
            height: 36px;
            box-sizing: border-box;
        }
        .el-input__inner {
            line-height: 36px;
        }
        .el-input-group__append .el-button {
            color: #409EFF;
            width: 100px;
            &.is-disabled {
                color: #999;
            }
        }
    }
    .desc {
        font-size: 14px;
        display: block;
        margin-bottom: 20px;
    }
}
</style>